import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import mail

import uuid
import random

import EventRecord

class CreateEvent( webapp.RequestHandler ):

  def post( self ):
    self.response.headers['Content-Type'] = 'text/html'

    title = self.request.get('title')
    date = self.request.get('date')
    time = self.request.get('time')
    venue = self.request.get('venue')
    email = self.request.get('email')

    if not title or not date or not time or not venue or not email:
      self.response.out.write('Fill in all the details to create event.')
      return
    if not mail.is_email_valid( email ):
      self.response.out.write('Use valid email address.')
      return

    record = EventRecord.EventRecord()
    record.id = str( uuid.uuid4() )
    record.passcode = str( random.randint( 1000, 9999 ) )
    record.title = title
    record.date = date
    record.time = time
    record.venue = venue
    record.email = email

    record.put()

    filling =  {
        'title' : record.title
      , 'date' : record.date
      , 'time' : record.time
      , 'venue' : record.venue
      , 'id' : record.id
      , 'passcode' : record.passcode
      , 'reg_link' : '%s?id=%s' % (
          self.request.relative_url('event')
        , record.id
      )
      , 'admin_link' : '%s?id=%s&passcode=%s' % (
          self.request.relative_url('admin')
        , record.id
        , record.passcode
      )
    }

    self.response.out.write(
'''
<h3>Event Created</h3>
<p>
  Title - %(title)s<br />
  Date - %(date)s<br />
  Time - %(time)s<br />
  Venue - %(venue)s<br />
  Event id - %(id)s<br />
  Event passcode - %(passcode)s<br />
<br />
  Event registration page - <a href="%(reg_link)s">%(reg_link)s</a><br />
  Event admin page - <a href="%(admin_link)s">%(admin_link)s</a><br />
</p>
''' % filling )

    mail.send_mail(
      sender = "misc.app@gmail.com",
      to = record.email,
      subject = "[Misc-App] Event Created",
      body =
'''
Hi,

Your event is created.
  Title - %(title)s
  Date - %(date)s
  Time - %(time)s
  Venue - %(venue)s
  Event id - %(id)s
  Event passcode - %(passcode)s

  Event registration page - %(reg_link)s
  Event admin page - %(admin_link)s

--
Misc-App Collection.
''' % filling )
  # end of CreateEvent.post

# end of class CreateEvent
